<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 订单模型
 */
class Order extends Model
{

    // 表名
    protected $name = 'order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

        // 追加属性
    protected $append = [
        'create_time_text',
        
    ];
        public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    
    public function order_add_together($user_id,$order,$goods_id_array){

        $order_no = $this->orderNo();

        $order['order_no'] = $order_no;
        $order['user_id'] = $user_id;

        foreach ($goods_id_array as $key => $value) {
            $goods_data = Db::name('litestore_goods')->where(['goods_id'=>$value['goods_id']])->find();
            // deduct_stock_type 库存计算方式:10=下单减库存,20=付款减库存
            if($goods_data['deduct_stock_type']==10){
                Db::name('litestore_goods_spec')->where('goods_spec_id',$value['goods_spec_id'])->setDec('stock_num',$value['num']);//减库存
                Db::name('litestore_goods_spec')->where('goods_spec_id',$value['goods_spec_id'])->setInc('sale_num',$value['num']);//增加销售量
            }
        }

        $this->save($order);
        return $order;
    }

    public function order_add($user_id){


        $order_no = $this->orderNo();

        $order['total_price'] = 365;

        $order['order_no'] = $order_no;
        
        $order['user_id'] = $user_id;

        $vip_time = Db::name('user')->where(['id'=>$user_id])->value('vip_time');
        if($vip_time)$order['order_type'] = 2;

        $add_id = $this->save($order);

        empty($add_id);
        Db::commit();
        return $order;
    }

    protected function orderNo()
    {
        return 'WM'.date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

}
